package sample.controller.category;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.util.BeanMap;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class IndexController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger =
        Logger.getLogger(IndexController.class.getName());

    @Override
    public Navigation run() {
        DatastoreService datastoreService =
            DatastoreServiceFactory.getDatastoreService();
        // 検索
        Query q = new Query("Category"); // KIND：Categoryを検索
        PreparedQuery pq = datastoreService.prepare(q);
        List<Entity> result = pq.asList(FetchOptions.Builder.withOffset(0));
        List<BeanMap> list = new ArrayList<BeanMap>();
        for (Entity e : result) {
            BeanMap m = new BeanMap();
            m.put("key", KeyFactory.keyToString(e.getKey()));
            m.put("name", e.getProperty("name"));
            list.add(m);

            // カテゴリに紐づくTodoの一覧を取得
            q = new Query("Todo", e.getKey());
            List<Entity> todos =
                datastoreService.prepare(q).asList(
                    FetchOptions.Builder.withOffset(0));
            List<BeanMap> todoList = new ArrayList<BeanMap>();
            for (Entity t: todos) {
                BeanMap m2 = new BeanMap();
                m2.put("content", t.getProperty("content"));
                todoList.add(m2);
            }
            m.put("todos", todoList);
        }
        requestScope("list", list);
        return forward("index.jsp");
    }
}
